<template>
  <div class="app-container">
    <el-card>
      <div class="app__body__container">
        <div class="ma__b__15">
          <el-button
            type="success"
            :icon="Plus"
            @click="showAddRoleDialog({ isEdit: false, row: null })"
            >新增</el-button
          >
        </div>
        <el-table
          :data="tableData"
          :border="parentBorder"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column type="expand">
            <template #default="props">
              <div class="app__children__table__container">
                <el-table :data="props.row.children" :border="childBorder">
                  <el-table-column label="角色组名称" prop="name" />
                  <el-table-column label="角色组权限">
                    <template #default="props">
                      <div
                        class="app__tag__list__container"
                        v-if="props.row.rules?.split(',')?.length"
                      >
                        <div
                          class="tag__list__item__container"
                          v-for="ruleItem in props.row.rules.split(',')"
                          :key="ruleItem"
                        >
                          <el-tag type="success" effect="dark">
                            {{ getPermissionName(Number(ruleItem)) }}
                          </el-tag>
                        </div>
                      </div>
                      <div class="empty__text" v-else>暂无权限</div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    fixed="right"
                    width="250"
                    align="center"
                  >
                    <template #default="props">
                      <div>
                        <el-button
                          type="primary"
                          @click="
                            showAddRoleDialog({ isEdit: true, row: props.row })
                          "
                          :icon="Edit"
                          >编辑</el-button
                        >
                        <el-button
                          type="danger"
                          :icon="Delete"
                          @click="delRow(props.row.id)"
                          >删除</el-button
                        >
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="角色组名称" prop="name" />
          <el-table-column label="角色组权限">
            <template #default="props">
              <div
                class="app__tag__list__container"
                v-if="props.row.rules?.split(',')?.length"
              >
                <div
                  class="tag__list__item__container"
                  v-for="ruleItem in props.row.rules.split(',')"
                  :key="ruleItem"
                >
                  <el-tag type="success" effect="dark">
                    {{ getPermissionName(Number(ruleItem)) }}
                  </el-tag>
                </div>
              </div>
              <div class="empty__text" v-else>暂无权限</div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            width="250"
            align="center"
          >
            <template #default="props">
              <div>
                <el-button
                  type="primary"
                  @click="showAddRoleDialog({ isEdit: true, row: props.row })"
                  :icon="Edit"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  :icon="Delete"
                  @click="delRow(props.row.id)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <AddRoleDialog ref="addRoleDialogRef" @success="addRoleDialogSuccess" />
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: "Role",
  inheritAttrs: false,
});

import AddRoleDialog from "./components/AddRoleDialog.vue";
import { getAdminGroupList, deleteAdminGroup } from "@/api/role/index";
import { getPermissionList } from "@/api/permission/index";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";

// 获取权限组列表
const parentBorder = ref(true);
const childBorder = ref(true);
const tableData = ref<any[]>([]);
const permissionList = ref<any[]>([]);
const loading = ref<boolean>(false);

// 获取角色组列表
const getAdminGroupListService = async () => {
  let params = {};
  loading.value = true;
  let res = await getAdminGroupList(params);
  loading.value = false;
  if (res) {
    console.log("获取角色组成功啦  ", res);
    tableData.value = [...res.data.list];
  }
};
getAdminGroupListService();

// 获取权限列表
const getPermissionListService = async () => {
  let params = {};
  loading.value = true;
  let res = await getPermissionList(params);
  loading.value = false;
  if (res) {
    console.log("权限列表返回结果 ", res);
    permissionList.value = formatPermissionList(res.data.list);
    console.log("最后格式化好的permissionList ", permissionList.value);
  }
};
getPermissionListService();

// 把树形结构搞成单一数组返回
const formatPermissionList = (list: any[]): any[] => {
  let result = [];
  if (list && list.length > 0) {
    for (let i = 0, len = list.length; i < len; i++) {
      const targetObj = JSON.parse(JSON.stringify(list[i]));
      delete targetObj.children;
      result.push(targetObj);
      if (list[i].children && list[i].children.length > 0) {
        result = result.concat(formatPermissionList(list[i].children));
      }
    }
  }
  return result;
};

// 用于模板中获取权限名称
const getPermissionName = (id: number) => {
  let name = "未知权限";
  const findIndex = permissionList.value.findIndex(
    (elm) => Number(elm.id) === id
  );
  if (findIndex !== -1) {
    name =
      permissionList.value[findIndex].name ||
      permissionList.value[findIndex].label;
  }
  return name;
};

// 删除角色组
const delRow = (id: number) => {
  ElMessageBox.confirm("您确定要删除该角色组吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAdminGroupService(id);
    })
    .catch(() => {
      ElMessage({
        message: "已取消",
        type: "info",
      });
    });
};

// 调用删除角色组接口
const deleteAdminGroupService = async (id: number) => {
  let data = {};
  console.log("iddddd  ", id);
  let res = await deleteAdminGroup(String(id), data);
  if (res) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    getAdminGroupListService();
  }
};

const addRoleDialogRef = ref<typeof AddRoleDialog | null>(null);

const showAddRoleDialog = (data: { isEdit: boolean; row: any | null }) => {
  if (!addRoleDialogRef.value) return;
  addRoleDialogRef.value.handleOpen(data, tableData.value);
};

const addRoleDialogSuccess = () => {
  getAdminGroupListService();
};
</script>

<style lang="scss" scoped>
.app-container {
  .app__body__container {
    .app__body__btn__container {
      padding-bottom: 10px;
      margin-bottom: 10px;
      border-bottom: 1px solid var(--el-border-color);
    }
    .app__children__table__container {
      padding-left: 50px;
    }
  }
  .app__tag__list__container {
    display: flex;
    flex-wrap: wrap;
    .tag__list__item__container {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}
</style>
